package service.impl;

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.WinNT;
import constants.EPlatform;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import service.SystemCommandService;

import java.lang.reflect.Field;

/**
 * windows系统的命令实现
 *
 * @author admin
 */
@Service
public class WindowsSystemCommandServiceImpl implements SystemCommandService {
    private static final String PREFIX = "cmd /c ";

    @Override
    public EPlatform getType() {
        return EPlatform.Windows;
    }

    @Override
    public Process excuteCMDCommand(String cmdCommand) {
        System.out.println("执行Windows命令：{}" + cmdCommand);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(PREFIX + cmdCommand);
            return process;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void killProcessTree(Process process, String rtspUrl) {
        try {
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handl = f.getLong(process);
            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handl));
            int ret = kernel.GetProcessId(handle);
            Long pid = (long) ret;
            String cmd = getKillProcessTreeCmd(pid);
            Runtime rt = Runtime.getRuntime();
            Process killPrcess = rt.exec(cmd);
            killPrcess.waitFor();
            killPrcess.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getKillProcessTreeCmd(Long pid) {
        String result = "";
        if (pid != null) {
            result = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
        }
        return result;
    }
}
